<?php
/**
 * Created by PhpStorm.
 *  公共函数库
 * User: yangliu
 * Date: 2019-01-07
 * Time: 17:30
 */

/**
 *
 */
if (!function_exists('getTree')) {
    //列数，当前循环，总数组
    function getTree($array, $pid =0, $type = 0){

        //声明静态数组,避免递归调用时,多次声明导致数组覆盖
        static $list = [];
        foreach ($array as $key => $value){
            //第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
            if ($value['pid'] == $pid){
                //父节点为根节点的节点,级别为0，也就是第一级
                $value['leve'] = $type;
                $value['name'] .= $value['type'] == 1 ? "(半成品)" :" ";
                //把数组放到list中
                $list[] = $value;
                //把这个节点从数组中移除,减少后续递归消耗
                unset($array[$key]);
                //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
                getTree($array, $value['id'], $type+1);
            }
        }
        return $list;
    }
}

if(!function_exists('generateTree'))
{
    function generateTree($array){
        //第一步 构造数据
        $items = array();
        foreach($array as $value){
            $items[$value['id']] = $value;
        }
        //第二部 遍历数据 生成树状结构
        $tree = array();
        foreach($items as $key => $value){
            if(isset($items[$value['pid']])){
                $items[$value['pid']]['son'][] = &$items[$key];
            }else{
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }
}

if(!function_exists('getOrderNo'))
{
    /**
     * 生产订单号
     * @param $type  前缀
     * @return string
     */
    function getOrderNo($type)
    {
        list($usec) = explode(" ", microtime());
        $usec = substr(str_replace('0.', '', $usec), 0 ,6);
        return $ret = $type .'-'. date('Ymd') .'-'.  $usec;
    }
}